package nio.example.study.server.handler;

import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;
import nio.example.study.common.Operation;
import nio.example.study.common.RequestMessage;
import nio.example.study.common.auth.AuthOperation;
import nio.example.study.common.auth.AuthOperationResult;

@Slf4j
@ChannelHandler.Sharable
public class AuthHandler extends SimpleChannelInboundHandler<RequestMessage> {
	@Override
	protected void channelRead0(ChannelHandlerContext ctx, RequestMessage msg) throws Exception {
		try {
			Operation operation = msg.getMessageBody();
			if (operation instanceof AuthOperation) {
				AuthOperation authOperation = AuthOperation.class.cast(operation);
				AuthOperationResult authOperationResult = authOperation.execute();
				if (authOperationResult.isPassAuth()) {
					log.info("pass auth");
				} else {
					log.error("fail to auth");
					ctx.close();
				}
			} else {
				log.info("expect first msg is auth");
				ctx.close();
			}
		} catch (Exception e) {
			log.info("exception happen:{}", e.getMessage(), e);
			ctx.close();
		} finally {
			// 第一次授权成功下一次就不用授权了
			ctx.pipeline().remove(this);
		}


	}
}
